package Homework03;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Homework03Client
{
    public static void main(String[] args) throws Exception
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入下载文件名");
        String downloadFileName = scanner.next();
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(downloadFileName.getBytes());
        socket.shutdownOutput();

        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        byte[] data = streamToByteArray(bufferedInputStream);
        String filePath = "D:\\Jave\\Internet\\src\\Homework03"+downloadFileName+".mp3";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath));
        bufferedOutputStream.write(data);

        bufferedOutputStream.close();
        bufferedInputStream.close();
        outputStream.close();
        socket.close();
        System.out.println("客服端退出");


    }
    public static byte[] streamToByteArray(InputStream is) throws  Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1)
        {
            bos.write(b,0,len);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return  array;
    }

}
